// oDPF51Klfz6EEnVTBC8E--qEQe7c
// oDPF51MxUoEmBbziEpG4OzOb3UKA

// oKWcP0ZKMAk5KuUFgsLyBRtAFt08
// oKWcP0aH_gzDA7ZAly-G9X56EUT0

// "{ 'thing1': { 'value': '微信小程序开发' }, 'time5': { 'value': '2023-04-09' }, 'name8': { 'value': '张三' } }"

// {
// 	"template_id": "X8m17h2BWcvrl_oyvu0XqGT67jolMb6nqq2sX8zG85g",
// 	"page": "",
// 	"touser": "oKWcP0ZKMAk5KuUFgsLyBRtAFt08",
// 	"data": "{
// 		'thing1': '{
// 			"value": "微信小程序开发"
// 		}'',
// 		"time5": {
// 			"value": "2023-04-09"
// 		},
// 		"name8": {
// 			"value": "张三"
// 		}
// 	}"
// }

const crypto = require("crypto");

function decryptData(sessionKey, encryptedData, iv) {
  // base64 decode
  var sessionKey = Buffer.from(sessionKey, "base64");
  encryptedData = Buffer.from(encryptedData, "base64");
  iv = Buffer.from(iv, "base64");

  try {
    // 解密
    var decipher = crypto.createDecipheriv("aes-128-cbc", sessionKey, iv);
    // 设置自动 padding 为 true，删除填充补位
    decipher.setAutoPadding(true);
    var decoded = decipher.update(encryptedData, "binary", "utf8");
    decoded += decipher.final("utf8");

    decoded = JSON.parse(decoded);

    return decoded;
  } catch (err) {
    throw new Error("Illegal Buffer");
  }
}

var sessionKey = "tiihtNczf5v6AKRyjwEUhQ==";
var encryptedData =
  "CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZM" +
  "QmRzooG2xrDcvSnxIMXFufNstNGTyaGS" +
  "9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+" +
  "3hVbJSRgv+4lGOETKUQz6OYStslQ142d" +
  "NCuabNPGBzlooOmB231qMM85d2/fV6Ch" +
  "evvXvQP8Hkue1poOFtnEtpyxVLW1zAo6" +
  "/1Xx1COxFvrc2d7UL/lmHInNlxuacJXw" +
  "u0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn" +
  "/Hz7saL8xz+W//FRAUid1OksQaQx4CMs" +
  "8LOddcQhULW4ucetDf96JcR3g0gfRK4P" +
  "C7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB" +
  "6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns" +
  "/8wR2SiRS7MNACwTyrGvt9ts8p12PKFd" +
  "lqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYV" +
  "oKlaRv85IfVunYzO0IKXsyl7JCUjCpoG" +
  "20f0a04COwfneQAGGwd5oa+T8yO5hzuy" +
  "Db/XcxxmK01EpqOyuxINew==";
var iv = "r7BXXKkLb8qrSNn05n0qiA==";

const data = decryptData(sessionKey, encryptedData, iv);
console.log(data);
